package com.wang.mvchain.common.util;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * html解析工具类
 * 
 * @author wangsh
 *
 */
public class HtmlParserUtil
{
	/**
	 * 获取美元人民币的汇率
	 * 
	 * @return
	 */
	public JSONObject findCoinrateRate(JSONObject condJSON)
	{
		return usdCnyOkex();
	}
	
	/**
	 * 从okex上获取usdcny的汇率
	 * 
	 * https://www.okex.me/v2/futures/market/indexTicker.do?symbol=f_usd_btc
	 * @return
	 */
	private JSONObject usdCnyOkex()
	{
		JSONObject resultJSON = new JSONObject();
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("requestURL",
				"https://www.okex.me/v2/futures/market/indexTicker.do?symbol=f_usd_btc");

		try
		{
			HTTPUtil httpUtil = new HTTPUtil();
			String response = httpUtil.methodGet(paramsMap);
			JSONObject responseJSON = (JSONObject) JSON.parse(response);
			if("0".equalsIgnoreCase(responseJSON.getString("code")))
			{
				JSONObject responseDataJSON = responseJSON.getJSONObject("data");
				JSONObject usdJSON = new JSONObject();
				usdJSON.put("id", "1");
				usdJSON.put("from", "USDT");
				usdJSON.put("to", "CNY");
				usdJSON.put("rate", responseDataJSON.get("usdCnyRate"));
				resultJSON.put("1", usdJSON);
			}
		} catch (Exception e)
		{
			/* 如果抛异常了,将汇率的默认值为1 */
			JSONObject usdJSON = new JSONObject();
			usdJSON.put("id", "1");
			usdJSON.put("from", "USDT");
			usdJSON.put("to", "CNY");
			usdJSON.put("rate", "1");
			resultJSON.put("1", usdJSON);
		}
		return resultJSON ; 
	}
	
	/**
	 * 从新浪获取usd对cny的汇率
	 * @return
	 */
	private JSONObject usdCnySina()
	{
		JSONObject resultJSON = new JSONObject();
		// 获取当时的美元与人民币的汇率
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("requestURL",
				"http://hq.sinajs.cn/?rn=" + System.currentTimeMillis()
						+ "&list=USDCNY");

		HTTPUtil httpUtil = new HTTPUtil();
		String response = httpUtil.methodGet(paramsMap);
		// ConstatFinalUtil.SYS_LOG.info(response + "------>");
		if (response != null && !"".equalsIgnoreCase(response))
		{
			String[] datas = response.split(",");
			JSONObject usdJSON = new JSONObject();
			usdJSON.put("id", "1");
			usdJSON.put("from", "USD");
			usdJSON.put("to", "CNY");
			usdJSON.put("rate", datas[1]);
			resultJSON.put("1", usdJSON);
		}
		return resultJSON;
	}

	public static void main(String[] args)
	{
		HtmlParserUtil htmlParserUtil = new HtmlParserUtil();
		JSONObject reqJSON = new JSONObject();
		JSONObject resJSON = htmlParserUtil.findCoinrateRate(reqJSON);
		ConstatFinalUtil.SYS_LOG.info("var response = " + resJSON);
	}
}
